package com.newsmanagement.util;

import com.newsmanagement.entity.RoleEntity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * @author xbr
 * 2017/12/5
 * 实体和map相互转换
 */
public class EntityMapChange {

    public static void main(String[] args) {

        Map<String ,Object> map = new HashMap<String ,Object>();

        map.put("CREATE_DATE" ,"2017-12-07 15: 03: 14.0");
        map.put("CREATE_USER" ,"1");
        map.put("UPDATE_DATE" ,"2017-12-07 15: 03: 14.0");
        map.put("UPDATE_USER" ,"1");
        map.put("DELETE_FLAG" ,"1");
        map.put("ROLE_ID" ,"4");
        map.put("ROLE_NAME" ,"juesemingcheng");

        map = changeKeyUpperToLower(map);

        RoleEntity role = new RoleEntity();

        role = mapToEntity(map, RoleEntity.class);

        System.out.println(role.toString());

    }
    
    /**
     * 将List<Map>转为List<Entity>
     * @param list
     * @param clazz
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static List<Object> mapToEntityList(List<Map<String ,Object>> list ,Class clazz){
        
    	if (null == clazz || null == list || list.size() < 1) {
			return null;
		}
    	
    	List list2 = new ArrayList<Object>();
    	Map<String ,Object> map = null;
    	for (int i = 0; i < list.size(); i++) {
    		map = list.get(i);
    		if (null != map) {
                list2.add(mapToEntity(map, clazz));
			}
		}
    	return list2;
    }
    
    /**
     * 将map转为entity
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T mapToEntity(Map<String ,Object> map ,Class<T> clazz){

        map = changeKeyUpperToLower(map);

    	if (null == clazz) {
			return null;
		}
    	
    	T thisEntity = null;
		try {
			thisEntity = clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e1) {
			e1.printStackTrace();
		}
		if (null == thisEntity) {
			return null;
		}
		
        //Get the methods
        Method[] methods = clazz.getDeclaredMethods();

		//方法名称
        String methodName = "";

        Field[] fields = clazz.getDeclaredFields();
        for (Method method : methods) {

            methodName = method.getName();

            if (methodName.startsWith("set")){
                methodName = methodName.substring(3);
                methodName = methodName.substring(0 ,1).toLowerCase() + methodName.substring(1);

                try {
                    for (Field field : fields) {
                        if (field.getName().equals(methodName)){

                        	//参数类型判断
                            String dataType = field.getType().getSimpleName();
                            if(dataType.equals("String")){
                            	method.invoke(thisEntity,map.get(methodName));
                            }else if(dataType.equals("Integer")){
                                System.out.println(Integer.valueOf(map.get(methodName) + ""));
                                method.invoke(thisEntity,Integer.valueOf(map.get(methodName) + ""));
                            }else if(dataType.equals("Long")){
                            	method.invoke(thisEntity,Long.valueOf(map.get(methodName) + ""));
                            }else if(dataType.equals("Float")){
                            	method.invoke(thisEntity,Float.valueOf(map.get(methodName) + ""));
                            }else if(dataType.equals("Double")){
                            	method.invoke(thisEntity,Double.valueOf(map.get(methodName) + ""));
                            }else if(dataType.equals("Timestamp")){
                            	method.invoke(thisEntity,CheckAndChangeUtil.getStrToTimestamp(map.get(methodName) + "", null, null, null));
                            	
                            }
                        }

                    }
                }catch (Exception e){

                }
            }
        }
    	return thisEntity;
    }

    /**
     * 将map中的key 如USER_NAME转为userName
     * @param map 要转换的数据
     * @return Map<String ,Object>
     */
    public static Map<String ,Object> changeKeyUpperToLower(Map<String ,Object> map){
        if (null == map){
            return null;
        }
        Map<String ,Object> resultMap = new HashMap<String ,Object>();
        for (String key : map.keySet()) {
            resultMap.put(changeKeyUpperToLower(key),map.get(key));
        }
        return resultMap;
    }

    /**
     * 功能：将大写转为下划线,且小写 如: USER_NAME > userName
     * @param key map的key
     * @return String
     */
    public static String changeKeyUpperToLower(String key){
        StringBuilder result = new StringBuilder();

        if ((key != null) && (key.length() > 0)) {

            //转为小写并拆分
            String[] stringArray = key.toLowerCase().split("_");
            result.append(stringArray[0]);
            for (int i = 1; i < stringArray.length; i++) {
                result.append(stringArray[i].substring(0 ,1).toUpperCase());
                result.append(stringArray[i].substring(1));
            }
        }
        return result.toString();
    }

}
